<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-input
            v-model="searchEntity.entity.username"
            placeholder="请输入用户名"
            @keyup.enter.native="search"
          />
        </el-col>
        <el-col :span="18">
          <el-button type="primary" @click="search">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="filter-container">
      <el-button
        v-permission="['ROLE_SUPERADMIN', 'system:user:addnew']"
        type="primary"
        @click="toAdd"
      ><i class="el-icon-plus" />添加用户</el-button>
    </div>
    <!-- 用户列表 -->
    <el-table :data="tableData" stripe border style="width: 100%">
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="username" label="姓名" width="180" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="mobile" label="手机" />
      <el-table-column prop="sysCode" label="用户编码" />
      <el-table-column
        prop="userType"
        :formatter="rendererUserType"
        label="用户类型"
      />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="isEnable" label="是否启用">
        <template slot-scope="scope">
          {{ scope.row.isEnable === 1 ? "启用" : "禁用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <el-button
            type="success"
            @click="grantRole(scope.row.id)"
          >分配角色</el-button>
          <el-button
            type="warning"
            @click="modifyUser(scope.row.id)"
          >修改</el-button>
          <el-button
            v-if="scope.row.userType != 1"
            type="danger"
            @click="removeUser(scope.row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="searchEntity.totalRecords"
      @current-change="jumpPagination"
    />
    <!-- 添加/修改用户弹出层 -->
    <el-dialog
      :title="dialogType"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form
        ref="formData"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="formData.username" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formData.mobile" type="text" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isEnable">
              <el-radio-group v-model="formData.isEnable">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="grantDialogVisible"
      width="500px"
    >
      <el-table
        ref="multipleTable"
        :data="roleList"
        tooltip-effect="light"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-row>
          <el-col
            :span="10"
          ><el-table-column label="角色名称" prop="roleName" /></el-col>
          <el-col
            :span="4"
          ><el-table-column type="selection" /></el-col>
          <el-col
            :span="10"
          ><el-table-column label="角色编码" prop="roleCode" /></el-col>
        </el-row>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="grantDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveGrant">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  userList,
  addUser,
  removeUser,
  getUserById,
  updateUser
} from '@/api/user'
import { getRolesByUserId, grantRole } from '@/api/role'
import { getRepeatToken } from '@/api/global'
import permission from '@/directive/permission/index.js'
import { deepClone } from '@/utils'
export default {
  name: 'UserIndex',
  directives: {
    permission
  },
  data() {
    var validateMovile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号'))
      } else if (/^1[3-9][0-9]{9}$/.test(value) != true) {
        return callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    var validateEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入邮箱'))
      } else if (
        /^\w{3,}(\.\w+)*@[a-z0-9]+(\.[a-z]{2,5}){1,2}$/i.test(value) != true
      ) {
        return callback(new Error('请输入正确的邮箱'))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      searchEntity: {
        pageNum: 1,
        pageSize: 10,
        entity: {
          username: ''
        },
        totalRecords: 0
      },
      repeatToken: '',
      formData: {
        sysCode: '', // 系统码
        sex: 1, // 性别（1：男；2：女）
        mobile: '', // 手机号
        portrait: '', // 头像
        orgId: '', // 机构ID暂不使用
        isEnable: 1, // 是否启用
        password: '', // 密码（无需考虑）
        id: '1', // 用户ID
        userType: 2, // 用户类型（1：超级管理员;2：普通用户）
        email: '', // 邮箱
        username: '' // 用户名
      },
      temp: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 12,
            message: '长度在 6 到 12 个字符',
            trigger: 'blur'
          }
        ],
        mobile: [{ validator: validateMovile, trigger: 'blur' }],
        email: [{ validator: validateEmail, trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogType: '添加用户',
      grantDialogVisible: false,
      roleList: [],
      selectRoles: [],
      currentUserId: ''
    }
  },
  created() {
    this.temp = deepClone(this.formData)
    this.initData()
  },
  methods: {
    initData() {
      getRepeatToken().then((res) => {
        this.repeatToken = res.data.token
      })
      userList(this.searchEntity).then((res) => {
        this.searchEntity.totalRecords = res.data.pageInfo.total
        this.tableData = res.data.pageInfo.list
      })
    },
    rendererUserType(row, column, cellValue, index) {
      if (cellValue === 1) {
        return '超级管理员'
      } else if (cellValue === 2) {
        return '普通用户'
      }
    },
    toAdd() {
      this.formData = deepClone(this.temp)
      this.dialogType = '添加用户'
      this.dialogFormVisible = true
    },
    saveUser() {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          if (this.dialogType == '添加用户') {
            addUser(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('操作成功!')
                  this.dialogFormVisible = false
                }
                this.initData()
              })
              .catch((err) => {
                this.initData()
              })
          } else {
            updateUser(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('操作成功!')
                  this.dialogFormVisible = false
                }
                this.initData()
              })
              .catch((err) => {
                this.initData()
              })
          }
        } else {
          return false
        }
      })
    },
    removeUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          removeUser(id, { token: this.repeatToken }).then((res) => {
            if (res.meta.code == 200) {
              this.initData()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    modifyUser(id) {
      getUserById(id).then((res) => {
        this.formData = res.data.data
        this.formData.password = ''
        this.dialogType = '修改用户'
        this.dialogFormVisible = true
      })
    },
    search() {
      if (!this.searchEntity.entity.username) { return this.$message.warning('请输入用户名进行查询') }
      this.searchEntity.pageNum = 1
      this.initData()
    },
    jumpPagination(num) {
      this.searchEntity.pageNum = num
      this.initData()
    },
    grantRole(id) {
      getRolesByUserId(id, { token: this.repeatToken }).then((res) => {
        this.roleList = res.data.list
        this.currentUserId = id
        this.roleList.forEach((row) => {
          if (row.selected) {
            this.$nextTick(() => {
              this.$refs.multipleTable.toggleRowSelection(row)
            })
          }
        })
        this.grantDialogVisible = true
      })
    },
    handleSelectionChange(selection) {
      /**
       *permId: "",//权限或菜单ID(当前选择的用户id)
        roleId: "",//角色ID
        type: ""//类型（menu：菜单；perm：权限）
       */
      this.selectRoles = selection
    },
    saveGrant() {
      if (this.selectRoles && this.selectRoles.length) {
        const newArr = []
        this.selectRoles.map(v => {
          newArr.push({ roleId: v.id, userId: this.currentUserId })
        })
        grantRole(newArr, { token: this.repeatToken }).then((res) => {
          if (res.meta.code == 200) {
            this.$message.success('授权成功!')
            this.initData()
            this.grantDialogVisible = false
          }
        })
      }
    }
  }
}
</script>
